#include "Test.h"

Test::Test()
{

	//testLog();
	testPipe();

}
void Test::testPipe()
{
	BOOL ok = TRUE;
	HANDLE hStdInPipeRead = NULL;
	HANDLE hStdInPipeWrite = NULL;
	HANDLE hStdOutPipeRead = NULL;
	HANDLE hStdOutPipeWrite = NULL;

	// Create two pipes.
	SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
	ok = CreatePipe(&hStdInPipeRead, &hStdInPipeWrite, &sa, 0);
	if (ok == FALSE) return;
	ok = CreatePipe(&hStdOutPipeRead, &hStdOutPipeWrite, &sa, 0);
	if (ok == FALSE) return;

	//TCHAR szModuleName[MAX_PATH];
	STARTUPINFO si = { };
	si.cb = sizeof(STARTUPINFO);
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdError = hStdOutPipeWrite;
	si.hStdOutput = hStdOutPipeWrite;
	si.hStdInput = hStdInPipeRead;
	PROCESS_INFORMATION pi = { };

	//GetModuleFileName(NULL, szModuleName, MAX_PATH);

	LPWSTR moduleName = (LPWSTR)L"C:\\Windows\\System32\\cmd.exe";
	LPWSTR parameter = (LPWSTR)L"/c git commit -m \"log update info\"";//(LPWSTR)L"git commit -m \"log update info\"";
	LPWSTR  dir = (LPWSTR)L"C:\\Users\\laremehpe\\Desktop\\shutdown-service";

	ok = CreateProcess(moduleName, parameter, NULL, NULL, TRUE, 0, NULL, dir, &si, &pi);

	if (ok == FALSE) return;

	// Close pipes we do not need.
	CloseHandle(hStdOutPipeWrite);
	CloseHandle(hStdInPipeRead);

	// The main loop for reading output from the DIR command.
	char buf[1024 + 1] = { };
	DWORD dwRead = 0;
	DWORD dwAvail = 0;
	ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
	string logs = "";
	while (ok == TRUE)
	{
		buf[dwRead] = '\0';
		//OutputDebugStringA(buf);
		logs += buf;
		puts(buf);
		ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
	}

	writeFile("gitLog.txt", logs);

	// Clean up and exit.
	CloseHandle(hStdOutPipeRead);
	CloseHandle(hStdInPipeWrite);

	WaitForSingleObject(pi.hProcess, INFINITE);

	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);
}
void Test::testLog()
{
	writeFile("gitLog.txt", "xxxxxxxxxxxxxxxxxx");
}
void Test::writeFile(string path, string content)
{
	ofstream ofs;
	ofs.open((char*)path.c_str(), ios::out);

	ofs << content << endl;

	ofs.close();
}


